import Toast from '../../../component/Toast';
import { trim } from '../../../util/utils';
import { routerRedux } from 'dva/router';
import { getLoginSession, setLoginSession, removeLoginSession } from '../../../plugin/loginSession';
import { login, logout, getLoginSessionByChannelAndToken } from '../service/loginService';

const defaultState = {
  	account: '',
  	password: '',
  	keepLogin: true
}

export default {

	namespace: 'login',

	state: {...defaultState},
	
	reducers: {
  	
  		reset(state) {
			return {...state, ...defaultState};
		},
		
	  	accountChange(state, {payload}) {
	  		return {...state, account: payload};
	  	},
	  	
	  	passwordChange(state, {payload}) {
	  		return {...state, password: payload};
	  	},
	  	
	  	keepLoginChange(state, {payload}) {
	  		return {...state, keepLogin: payload};
	  	},
		
	},
	
	effects: {
		
		*init(action, {select, put}) {
			yield put({type: 'reset'});
			let loginSession = getLoginSession();
			if(loginSession) {
				let res = yield getLoginSessionByChannelAndToken();
				if(res.code == 1) {
					let {loginRedirect} = yield select(state => state.login);
					yield put(routerRedux.push(loginRedirect));
				}
			}
		},
		
		*login(action, {select, put}) {
			let {account, password, keepLogin, channel, loginRedirect} = yield select(state => state.login);
			if(!account || !(trim(account))) {
	  			yield Toast.show('账号不能为空');
	  		} else if(!password || !(trim(password))) {
				yield Toast.show('密码不能为空');
	  		} else {
	  			let res = yield login({channel, identity: account, certification: password});
				if(res && res.code == 1 && res.data) {
					setLoginSession(res.data);
					if(loginRedirect) 
						yield put(routerRedux.push(loginRedirect));
				} else {
					Toast.show(res.msg);
				}
	  		}
		},
		
		*logout(action, {select, put}) {
			let {logoutRedirect} = yield select(state => state.login);
			let loginSession = getLoginSession();
			if(loginSession) {
				let res = yield logout();
				if (res.code == 1) {
					removeLoginSession();
					if(logoutRedirect)
						yield put(routerRedux.push(logoutRedirect));
				} else {
					Toast.show(res.msg)
				}
			}
		}
		
	}
  
}
